﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Net;
using System.Collections;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using Microsoft.Phone.Shell;
using System.IO;


namespace CanalDeNoticiasMSDNv3.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        public const string _spain = "http://channel9.msdn.com/Blogs/channel9spain/RSS";
        public const string _noticiasLink = "http://www.microsoft.com/spain/msdn/rss/noticias.xml";
        public const string _articulosLink = "http://www.microsoft.com/spain/msdn/rss/articulos.xml";

        public DateTime? LastRefresh { get; set; }

        public MainViewModel()
        {
            Videos = new ObservableCollection<ElementoEntradaVideo>();
            Noticias = new ObservableCollection<ElementoEntradaRss>();
            Articulos = new ObservableCollection<ElementoEntradaRss>();
        }


        public ObservableCollection<ElementoEntradaVideo> Videos
        {
            get;
            set;
        }

        public ObservableCollection<ElementoEntradaRss> Noticias
        {
            get;
            set;
        }

        public ObservableCollection<ElementoEntradaRss> Articulos
        {
            get;
            set;
        }

        bool _error;
        public void LoadData()
        {
            fillVideos(_spain);
            fillRss(_articulosLink, Articulos);
            fillRss(_noticiasLink, Noticias);
        }

        private void fillVideos(string rssUrl)
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += (x, e) =>
            {
                if (e.Error == null)
                {
                    fillVideosList(e.Result);
                }
            };
            client.DownloadStringAsync(
                new Uri(rssUrl));
        }

        private void fillVideosList(string p)
        {
            List<ElementoEntradaVideo> elements = ElementoEntradaVideo.GetElements(p);
            this.Videos.Clear();

            elements.ForEach((element) => this.Videos.Add(element));
            this.LastRefresh = DateTime.Now;
        }

        private void fillRss(string rssUrl, ObservableCollection<ElementoEntradaRss> collection)
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += (x, e) =>
            {
                if (e.Error == null)
                {
                    fillRssList(collection, e.Result);
                }
            };
            client.DownloadStringAsync(
                new Uri(rssUrl));
        }

        private void fillRssList(ObservableCollection<ElementoEntradaRss> collection, string p)
        {
            collection.Clear();
            List<ElementoEntradaRss> elements = ElementoEntradaRss.GetElements(p);
            elements.ForEach((element) => collection.Add(element));
            this.LastRefresh = DateTime.Now;
        }

        const string keyName = "mainviewmodel";

        public void LoadFromIsolatedStorage()
        {
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (file.FileExists(keyName))
                {
                    using (IsolatedStorageFileStream stream = file.OpenFile(keyName, System.IO.FileMode.Open))
                    {
                        XmlSerializer ser = new XmlSerializer(this.GetType());
                        MainViewModel model = (MainViewModel)ser.Deserialize(stream);
                        loadModel(model);
                    }
                }
            }
        }

        public void SaveToIsolatedStorage()
        {
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream stream = file.OpenFile(keyName, System.IO.FileMode.Create))
                {
                    XmlSerializer ser = new XmlSerializer(this.GetType());
                    stream.Position = 0;
                    ser.Serialize(stream, this);
                }
            }
        }

        public void LoadFromState()
        {
            IDictionary<string, object> stateStore =
                    PhoneApplicationService.Current.State;

            if (stateStore.ContainsKey(keyName))
            {
                MainViewModel model = (MainViewModel)stateStore[keyName];
                loadModel(model);
            }
        }

        public void SaveToState()
        {
            IDictionary<string, object> stateStore =
                   PhoneApplicationService.Current.State;

            stateStore.Remove(keyName);
            stateStore.Add(keyName, this);
        }

        private void loadModel(MainViewModel model)
        {
            this.Articulos = model.Articulos;
            this.Noticias = model.Noticias;
            this.Videos = model.Videos;
            this.LastRefresh = model.LastRefresh;
        }

    }
}